package io.renren.modules.reception.controller;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.RRException;
import io.renren.common.utils.FastIDUtil;
import io.renren.common.utils.RedisUtils;
import io.renren.modules.constants.RedisConstants;
import io.renren.modules.member.entity.TStoreMemberAccountDetailEntity;
import io.renren.modules.member.entity.TStoreMemberConsumeRecordEntity;
import io.renren.modules.member.service.TStoreMemberAccountDetailService;
import io.renren.modules.member.service.TStoreMemberConsumeRecordService;
import io.renren.modules.member.service.TStoreMemberRuleService;
import io.renren.modules.reception.entity.vo.*;
import io.renren.modules.reception.init.TableThemeCache;
import io.renren.modules.reception.service.TStoreOpenDeskService;
import io.renren.modules.store.entity.TStoreAccountListEntity;
import io.renren.modules.store.entity.TStoreDiningTableEntity;
import io.renren.modules.store.service.TStoreAccountListService;
import io.renren.modules.store.service.TStoreAccountUnitService;
import io.renren.modules.store.service.TStoreDiningTableService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.reception.entity.TStoreOrderRecordEntity;
import io.renren.modules.reception.service.TStoreOrderRecordService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-02-09 13:23:50
 */
@RestController
@RequestMapping("reception/tstoreorderrecord")
public class TStoreOrderRecordController extends AbstractController {
    @Autowired
    private TStoreOrderRecordService tStoreOrderRecordService;
    @Autowired
    private TStoreDiningTableService tStoreDiningTableService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TStoreAccountUnitService accountUnitService;
    @Autowired
    private TStoreMemberRuleService memberRuleService;
    @Autowired
    private TStoreMemberAccountDetailService accountDetailService;
    @Autowired
    private TStoreMemberConsumeRecordService consumeRecordService;
    @Autowired
    private TStoreOpenDeskService openDeskService;
    @Autowired
    private TStoreAccountListService storeAccountListService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private TStoreDiningTableService diningTableService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("reception:tstoreorderrecord:list")
    public R list(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        Page<TangShiOrderRecordVo> page = tStoreOrderRecordService.listOrderRecord(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{orderId}")
    @RequiresPermissions("reception:tstoreorderrecord:info")
    public R info(@PathVariable("orderId") Long orderId){
		TStoreOrderRecordEntity tStoreOrderRecord = tStoreOrderRecordService.getById(orderId);

        return R.ok().put("tStoreOrderRecord", tStoreOrderRecord);
    }

    /**
     * 反结账
     */
    @RequestMapping("/backCheck")
    public R backCheck(@RequestParam Long id){
        TStoreOrderRecordEntity entity = tStoreOrderRecordService.getById(id);
        TStoreDiningTableEntity diningTable = tStoreDiningTableService.getOne(new QueryWrapper<TStoreDiningTableEntity>()
                .eq("dining_table_no", entity.getDiningTableNo())
        );
        if (diningTable.getStatus() != 1){
            throw new RRException("请确保"+diningTable.getDiningTableNo()+"桌为空闲状态");
        }
        //存入Redis
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOpenTime(entity.getOpenTime());
        orderInfo.setId(entity.getDeskId());
        orderInfo.setDiningTableNo(entity.getDiningTableNo());
        orderInfo.setEatNumer(entity.getEatNumer());
        orderInfo.setStaffName(entity.getStaffName());
        orderInfo.setDeskAnotherName(entity.getDeskAnotherName());
        orderInfo.setOrderId(entity.getOrderId());
        orderInfo.setOpenDeskRemark(entity.getOpenDeskRemark());
        orderInfo.setOrderId(entity.getOrderId());
        orderInfo.setTotalMoney(entity.getTotalMoney());
        List<FoodVo> foodVos = JSONArray.parseArray(entity.getFoodVo(), FoodVo.class);
        List<FoodVo> foodVoList = new ArrayList<>();
        for (FoodVo foodVo : foodVos){
            foodVo.setDiscount(null);
            foodVo.setDiscountMoney(null);
            foodVoList.add(foodVo);
        }
        orderInfo.setFoodVos(foodVoList);

        if (entity.getDiscountId() != null){
            orderInfo.setPreCheckSign(1);
        }
        if (entity.getMemberId() != null){
            orderInfo.setPreMemSign(1);
        }
        orderInfo.setDiscountMoney(0.0);
        orderInfo.setOpenTime(new Date());

        Map<String, Object> map = BeanUtil.beanToMap(orderInfo);
        redisTemplate.opsForHash().putAll(RedisConstants.OPEN_DESK_PREFIX+diningTable.getId() +RedisConstants.OPEN_DESK_SYMBOL+getSeller(),map);

        TStoreOrderRecordEntity storeOrderRecordEntity = new TStoreOrderRecordEntity();
        storeOrderRecordEntity.setId(id);
        storeOrderRecordEntity.setStatus(2);
        storeOrderRecordEntity.setReallyGet(0D);
        storeOrderRecordEntity.setDiscount(0D);
        storeOrderRecordEntity.setWipeZero(0D);
        storeOrderRecordEntity.setZero(0D);
        storeOrderRecordEntity.setRemark("");
        storeOrderRecordEntity.setPayMethodName("");
        storeOrderRecordEntity.setAccountId(null);
        storeOrderRecordEntity.setMemberId(null);
        storeOrderRecordEntity.setDiscountId(null);
        tStoreOrderRecordService.updateById(storeOrderRecordEntity);

        //将餐台置为用餐中
        tStoreDiningTableService.update(new UpdateWrapper<TStoreDiningTableEntity>()
            .eq("seller_id",getSeller())
                .eq("id",diningTable.getId())
                .set("status",2)
                .set("style", TableThemeCache.get(getSeller()).getEatColor())
        );
        return  R.ok();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("reception:tstoreorderrecord:save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody CheckoutVo checkoutVo){
        //保存订单信息------------------TODO 1
        checkoutVo.getOrderInfo().setSellerId(getSeller());
        Object json = JSONObject.toJSON(checkoutVo.getOrderInfo().getFoodVos());
        checkoutVo.getOrderInfo().setFoodVo(json.toString());
        checkoutVo.getOrderInfo().setEndTime(new Date());
        checkoutVo.getOrderInfo().setCreateUserName(getUser().getUsername());
        checkoutVo.getOrderInfo().setStatus(1);
        TStoreOrderRecordEntity entity = new TStoreOrderRecordEntity();
        TStoreOrderRecordEntity order = tStoreOrderRecordService.getOne(new QueryWrapper<TStoreOrderRecordEntity>()
                .eq("order_id", checkoutVo.getOrderInfo().getOrderId())
        );
        if (order != null){
            checkoutVo.getOrderInfo().setId(order.getId());
        }
        BeanUtil.copyProperties(checkoutVo.getOrderInfo(),entity);
		tStoreOrderRecordService.saveOrUpdate(entity);

        //删除缓存  TODO 2
        if (checkoutVo.getOrderInfo().getOpenDeskInfo().getMaster() == 1 ||
                checkoutVo.getOrderInfo().getOpenDeskInfo().getSlave() == 1){
            List<TStoreDiningTableEntity> list = null;
            if (checkoutVo.getOrderInfo().getOpenDeskInfo().getMaster() == 0){
                list = diningTableService.list(new QueryWrapper<TStoreDiningTableEntity>()
                        .eq("seller_id", getSeller())
                        .eq("master_id", checkoutVo.getOrderInfo().getOpenDeskInfo().getMasterId())
                        .or()
                        .eq("id", checkoutVo.getOrderInfo().getOpenDeskInfo().getMasterId())
                );
            }else {
                list = diningTableService.list(new QueryWrapper<TStoreDiningTableEntity>()
                        .eq("seller_id", getSeller())
                        .eq("master_id", checkoutVo.getOrderInfo().getOpenDeskInfo().getId())
                        .or()
                        .eq("id", checkoutVo.getOrderInfo().getOpenDeskInfo().getId())
                );
            }
            for (TStoreDiningTableEntity tStoreDiningTableEntity : list) {
                redisUtils.delete(RedisConstants.OPEN_DESK_PREFIX + tStoreDiningTableEntity.getId() +RedisConstants.OPEN_DESK_SYMBOL+ getSeller());
            }
        }else {
            redisUtils.delete(RedisConstants.OPEN_DESK_PREFIX+checkoutVo.getOrderInfo().getId()
                     +RedisConstants.OPEN_DESK_SYMBOL+checkoutVo.getOrderInfo().getSellerId());
        }

		//更新餐桌状态  TODO 3
        if (checkoutVo.getOrderInfo().getOpenDeskInfo().getMaster() == 0 && checkoutVo.getOrderInfo().getOpenDeskInfo().getSlave() == 0){
            TStoreDiningTableEntity diningTableEntity = new TStoreDiningTableEntity();
            diningTableEntity.setStyle(TableThemeCache.get(getSeller()).getWaitColor());
            diningTableEntity.setStatus(3);
            diningTableEntity.setId(checkoutVo.getOrderInfo().getOpenDeskInfo().getId());
            tStoreDiningTableService.updateById(diningTableEntity);
        }
        else {
            if (checkoutVo.getOrderInfo().getOpenDeskInfo().getMaster() == 1){
                  tStoreDiningTableService.update(new UpdateWrapper<TStoreDiningTableEntity>()
                        .set("master_id", 0)
                        .set("style",TableThemeCache.get(getSeller()).getWaitColor())
                        .set("status", 3)
                        .set("slave", 0)
                        .set("master",0)
                        .eq("seller_id",getSeller())
                        .eq("master_id", checkoutVo.getOrderInfo().getId())
                        .or()
                        .eq("id",checkoutVo.getOrderInfo().getId())
                );
            }else {
                TStoreDiningTableEntity tableEntity = tStoreDiningTableService.getById(checkoutVo.getOrderInfo().getOpenDeskInfo().getId());
                tStoreDiningTableService.update(new UpdateWrapper<TStoreDiningTableEntity>()
                        .set("master_id", 0)
                        .set("style", TableThemeCache.get(getSeller()).getWaitColor())
                        .set("status", 3)
                        .set("slave", 0)
                        .set("master",0)
                        .eq("seller_id",getSeller())
                        .eq("master_id", tableEntity.getMasterId())
                        .or()
                        .eq("id",tableEntity.getMasterId())
                );
            }
        }


        //挂账单位  TODO 4
        if (checkoutVo.getOrderInfo().getAccountId() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("accountId",checkoutVo.getOrderInfo().getAccountId());
            map.put("sellerId",getSeller());
            map.put("money",checkoutVo.getOrderInfo().getTotalMoney());
            accountUnitService.updateAccount(map);

            TStoreAccountListEntity storeAccountListEntity = new TStoreAccountListEntity();
            storeAccountListEntity.setAccountId(checkoutVo.getOrderInfo().getAccountId())
                    .setOrderId(checkoutVo.getOrderInfo().getOrderId())
                    .setMoney(checkoutVo.getOrderInfo().getTotalMoney())
                    .setCreateTime(new Date())
                    .setCreateUser(getUser().getUsername())
                    .setFoodVo(JSONObject.toJSON(checkoutVo.getOrderInfo().getFoodVos()).toString())
                    .setStatus(1)
                    .setType(1);
            storeAccountListService.save(storeAccountListEntity);
        }

        //  TODO 5
        if (checkoutVo.getOrderInfo().getMemberId() != null){
            //更新会员账户会员
            double exchangeIntegral = memberRuleService.ExchangeIntegral(getSeller(), checkoutVo.getOrderInfo().getMemberTypeId());
            Map<String, Object> map = new HashMap<>();
            TStoreMemberConsumeRecordEntity consumeRecordEntity = new TStoreMemberConsumeRecordEntity();
            List<PayVo> list = checkoutVo.getOrderInfo().getPayVo();
            for (PayVo payVo : list) {
                if (payVo.getPayMethodName().equals("储值卡")) {
                    double memberIntegral = Math.ceil(payVo.getPayMoney() * exchangeIntegral);
                    map.put("integral", memberIntegral);
                    map.put("amount", payVo.getPayMoney());
                    consumeRecordEntity.setConsumeAmout(payVo.getPayMoney());
                    map.put("memberId", checkoutVo.getOrderInfo().getMemberId());
                    accountDetailService.updateMemberAccountConsume(map);
                    //插入会员消费记录表
                    consumeRecordEntity.setCreateTime(new Date());
                    consumeRecordEntity.setCreateUserId(getUserId());
                    consumeRecordEntity.setMemberId(checkoutVo.getOrderInfo().getMemberId());
                    consumeRecordEntity.setOrderId(Long.parseLong(checkoutVo.getOrderInfo().getOrderId()));
                    consumeRecordEntity.setRemark(checkoutVo.getOrderInfo().getRemark());
                    consumeRecordEntity.setSellerId(getSeller());
                    consumeRecordEntity.setDiscount(checkoutVo.getOrderInfo().getDiscount());
                    consumeRecordService.save(consumeRecordEntity);
                }
            }
        }
       // tStoreOrderRecordService.placeOrder(checkoutVo);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("reception:tstoreorderrecord:update")
    public R update(@RequestBody TStoreOrderRecordEntity tStoreOrderRecord){
		tStoreOrderRecordService.updateById(tStoreOrderRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("reception:tstoreorderrecord:delete")
    public R delete(@RequestBody Long[] orderIds){
		tStoreOrderRecordService.removeByIds(Arrays.asList(orderIds));

        return R.ok();
    }

}
